require "http"

class Api::V1::IdentifyCodesController < Api::V1::BaseController
  skip_before_action :authenticate_request!

  def create
    if params[:type] == 'register'
      user = User.find_by_phone params[:phone]
      if user.blank?
        @temp_user = TempUser.find_or_create_by(phone: params[:phone])
        @temp_user.identify_code = rand(999999)
        @temp_user.action_type = 'register'
        @temp_user.save
        @reponse = Qcloud::Sms.single_sender(params[:phone], "268365", ["#{@temp_user.identify_code}"])
        render json: { result: true, message: '短信已发送.' }, status: :ok and return
      else
        render json: { result: false, message: '该手机已注册.' }, status: :ok and return
      end
    elsif params[:type] == 'password'
      @temp_user = TempUser.find_or_create_by(phone: params[:phone])
      @temp_user.identify_code = rand(999999)
      @temp_user.action_type = 'password'
      @temp_user.save
      @reponse = Qcloud::Sms.single_sender(params[:phone], "268365", ["#{@temp_user.identify_code}"])
      render json: { result: true, message: '短信已发送.' }, status: :ok and return
    elsif params[:type] == 'phone'
      @temp_user = TempUser.find_or_create_by(phone: params[:phone], old_phone: params[:old_phone])
      @temp_user.identify_code = rand(999999)
      @temp_user.action_type = 'phone'
      @temp_user.save
      @reponse = Qcloud::Sms.single_sender(params[:phone], "268365", ["#{@temp_user.identify_code}"])
      render json: { result: true, message: '短信已发送.' }, status: :ok and return
    else
      render json: { result: false, message: '不可用服务.' }, status: :ok and return
    end
  end
end
